<?php

namespace app\admin\controller;

use app\admin\model\OrderDispute;
use app\BaseController;
use app\dic\DicOrderDispute;
use think\App;

/**
 * @author xjw
 * @class:TaskorderDispute 定时任务=>争议订单操作
 * @method order_dispute 争议订单操作
 * @method deal_orders_dispute 处理争议订单
 * @return  
 */


class Taskorderdispute extends BaseController
{

    protected $model = null;
    protected $api = array();
    protected $api2 = array();
    protected $stripe_api = array();
    protected $stripe_api2 = array();

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new OrderDispute();
        $this->api['apikey'] = 'AbenrIbEmUYHrLdpmQ98Mesvuq7D9f9dujpYhwV9gGLls2XxsP7t3GFIH9p4Vi3kNjKuY3Fm1yMBvDf6';
        $this->api['apisecret'] = 'EPG2QoOokyzMcX0_838bUNCg4Iir59Skcmo2osiFfbDl7ZFgzaeKqCaGbbDB9OPy5dVJZA1fkKU0wDgm';

        $this->api2['apikey'] = 'AWw3AUTkVJlVVNV9IJRttLCC63IQnDuirrXS4xo6nOgkXfl4QvBVTzlJT1-bLJaa2CBlAhkfBccJwYn7';
        $this->api2['apisecret'] = 'EMOPVKAE-1AaGMXHgTiMUgM44t5m4pHC0iuqOj3CAj7IH_78Y-s-zMQtGTwX3GuGT2zswEwM57j8JGwN';

        $this->stripe_api = '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';
        $this->stripe_api2 = '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';
    }

    /**
     * 
     *  争议订单操作   
     *  type=3 获取更早之前的争议订单
     *  type=2 更新争议订单
     */
    public function  order_dispute_paypal()
    {
        $type = input('type');
        if (!$type) {
            return error('type不能为空');
        }
        $return = $this->deal_orders_dispute_paypal($type,$this->api,'01paypal');
        return success('操作成功',$return);
    }

    /**
     * 
     *  争议订单操作   
     *  type=3 获取更早之前的争议订单
     *  type=2 更新争议订单
     */
    public function  order_dispute_paypal02()
    {
        $type = input('type');
        if (!$type) {
            return error('type不能为空');
        }
        $return = $this->deal_orders_dispute_paypal($type,$this->api2,'02paypal');
        return success('操作成功',$return);
    }
    /**
     *  争议订单操作   
     *  type=3 获取更早之前的争议订单
     *  type=2 更新争议订单
     */
    public function deal_orders_dispute_paypal($type,$api,$number)
    {
        $url = "https://api-m.paypal.com/v1/customer/disputes";
        if ($type == DicOrderDispute::$type_3) {
            $order_dispute = table('order_dispute')
            ->where(['type' => 'paypal'])
            ->where(['number' => $number])
            ->order('update_time asc')
            ->find();
            if(!empty($order_dispute)){
                $url = $url . '?update_time_before=' . $order_dispute['update_time'];
            }
        }
        if ($type == DicOrderDispute::$type_2) {
            $order_dispute = table('order_dispute')
            ->where(['type' => 'paypal'])
            ->where(['number' => $number])
            ->order('createtime desc')->find();
            if(!empty($order_dispute)){
                $url = $url . '?start_time=' . $order_dispute['createtime'];
            }
        }
        if ($type == DicOrderDispute::$type_4) {
            $order_dispute = table('order_dispute')
            ->where(['type' => 'paypal'])
            ->where(['number' => $number])
            ->order('update_time desc')
            ->find();
            if(!empty($order_dispute)){
                $url = $url . '?update_time_after=' . $order_dispute['update_time'];
            }
        }
        $data =  $this->geturl_paypal($url,$api);
        if ($data) {
            $data = json_decode($data, true);
            if (!empty($data['error'])) {
                return $data['error_description'];
            }
            if(!empty($data['items']) && isset($data['items'])){
                $orders = $data['items'];
            }else{
                $orders = array();
            }
            if (is_array($orders) && !empty($orders)) {
                date_default_timezone_set('Asia/Shanghai');
                foreach ($orders as  $order) {
                    $order_info = $this->model->where(['dispute_id' => $order['dispute_id']])->find();
                    $arr['type'] = 'paypal';
                    $arr['createtime'] = $order['create_time'];
                    $arr['update_time'] = $order['update_time'];
                    $arr['status'] = $order['status'];
                    $arr['amount'] = $order['dispute_amount']['value'];
                    $arr['currency'] = $order['dispute_amount']['currency_code'];
                    $arr['number'] = $number;

                    $href = $order['links'][0]['href'];
                    $data2 =  $this->geturl_paypal($href,$api);
                    if ($data2) {
                        $data2 = json_decode($data2, true);
                        if (empty($data2['error'])) {
                            if(isset($data2['disputed_transactions'][0])){
                                $disputed_transactions = $data2['disputed_transactions'][0];
                            }else{
                                $disputed_transactions = array();
                            }
                            if(!empty($disputed_transactions)){
                                $arr['customer_name'] = $disputed_transactions['buyer']['name'];
                                $arr['seller_transaction_id'] = $disputed_transactions['seller_transaction_id'];
                                $arr['invoice_number'] = $disputed_transactions['invoice_number'];
                                if(isset($disputed_transactions['items'][0])){
                                    $disputed_items = $disputed_transactions['items'][0];
                                    if(!empty($disputed_items)){
                                        if(isset($disputed_items['item_name'])){
                                            $arr['item_name'] = $disputed_items['item_name'];
                                        }
                                        if(isset($disputed_items['item_quantity'])){
                                            $arr['item_quantity'] = $disputed_items['item_quantity'];
                                        }
                                        if(isset($disputed_items['item_description'])){
                                            $arr['item_description'] = $disputed_items['item_description'];
                                        }
                                        
                                    }
                                }
                            }
                            $arr['reason'] = $data2['reason'];
                        }
                    }
                    if ($order_info) {
                        if(strtotime($order_info['update_time']) > strtotime($arr['update_time'])){
                            $this->model->where(['dispute_id' => $order['dispute_id']])->update($arr);
                        }
                    } else {
                        $arr['dispute_id'] = $order['dispute_id'];
                        $this->model->insert($arr);
                    }
                }
            }
        }
        return 1;
    }

    /**
    * 方法详情
    * @param array params
    */
    public function details_paypal()
    {
        $return = 0;
        $url = "https://api-m.paypal.com/v1/customer/disputes/PP-R-TVX-487946819";
        $url = "https://api-m.paypal.com/v1/customer/disputes/PP-R-QZH-483031516";
        $data =  $this->geturl_paypal($url,$this->api2);
        if ($data) {
            $data = json_decode($data, true);
            halt($data);
        }
        return $return;
    }
    
    /**
     * 
     *  争议订单操作   
     *  type=3 获取更早之前的争议订单  5分钟执行一次
     *  type=2 更新争议订单  15分钟执行一次
     */
    public function order_dispute()
    {
        $type = input('type');
        if (!$type) {
            return error('type不能为空');
        }
        $return = $this->deal_orders_dispute($type,$this->stripe_api,'01stripe');
        return success('操作成功',$return);
    }

    public function order_dispute02()
    {
        $type = input('type');
        if (!$type) {
            return error('type不能为空');
        }
        $return = $this->deal_orders_dispute($type,$this->stripe_api2,'02stripe');
        return success('操作成功',$return);
    }

    public function dispute_info()
    {
        $url = "https://api.stripe.com/v1/disputes/du_1NOD6nIDYTVHVI66yXP4gaXE";
        $data =  $this->geturl($url,$this->stripe_api2);
        if ($data) {
            $data = json_decode($data, true);
            halt($data);
        }
    }
    /**
     * 处理订单=>更新order表和site.updatetime_order字段
     *   获取订单  时间条件 site.updatetime_order
     *   更新订单  时间条件 order.ycreated_at
     */

    public function deal_orders_dispute($type,$api,$number)
    {
        $url = "https://api.stripe.com/v1/disputes?limit=50";
        if ($type == DicOrderDispute::$type_3) {
            $order_dispute = $this->model
            ->where(['type' => 'stripe'])
            ->where(['number' => $number])
            ->order('createtime asc')->find();
            if(!empty($order_dispute)){
                $url = $url . '&starting_after=' . $order_dispute['dispute_id'];
            }
        }
        if ($type == DicOrderDispute::$type_2) {
            $order_dispute = $this->model
            ->where(['type' => 'stripe'])
            ->where(['number' => $number])
            ->order('createtime desc')->find();
            if(!empty($order_dispute)){
                $url = $url . '&ending_before=' . $order_dispute['dispute_id'];
            }
        }
        if ($type == DicOrderDispute::$type_4) {
            $time = time() - 2592000; 
            $where_createtime[]  = ['createtime', '>=', $time];
            $order_dispute = $this->model
                ->where(['type' => 'stripe'])
                ->where(['number' => $number])
                ->where($where_createtime)
                ->order('update_time asc')
                ->find();
            if(!empty($order_dispute)){
                $url = "https://api.stripe.com/v1/disputes/". $order_dispute['dispute_id'];
            }
        }
        $data =  $this->geturl($url,$api);
        if ($data) {
            $data = json_decode($data, true);
            if ($type == DicOrderDispute::$type_4) {
                $orders[] = $data;
            }else{
                if (!empty($data['error'])) {
                    return $data['error']['message'];
                }
                $orders = $data['data'];
            }
            if (is_array($orders) && !empty($orders)) {
                date_default_timezone_set('Asia/Shanghai');
                foreach ($orders as  $order) {
                    $order_info = $this->model->where(['dispute_id' => $order['id']])->find();
                    $arr['type'] = 'stripe';
                    $arr['createtime'] = $order['created'];
                    $arr['status'] = $order['status'];
                    $arr['number'] = $number;
                    $arr['reason'] = $order['reason'];
                    $arr['payment_intent'] = $order['payment_intent'];
                    $arr['amount'] = $order['amount'];
                    if(isset($order['balance_transactions'][0])){
                        $balance_transactions = $order['balance_transactions'][0];
                        if(!empty($balance_transactions)){
                            $arr['fee'] = $balance_transactions['fee'];
                        }
                    }
                    $arr['currency'] = $order['currency'];
                    $arr['customer_email_address'] = $order['evidence']['customer_email_address'];
                    $arr['customer_name'] = $order['evidence']['customer_name'];
                    $arr['billing_address'] = $order['evidence']['billing_address'];
                    $arr['shipping_address'] = $order['evidence']['shipping_address'];
                    if ($order_info) {
                        $this->model->where(['dispute_id' => $order['id']])->update($arr);
                    } else {
                        $arr['dispute_id'] = $order['id'];
                        $this->model->insert($arr);
                    }
                }
            }
        }
        return 1;
    }
    /**
     *更新争议订单
     */
    public function update_orders_dispute($id = null)
    {
        if (!empty($id)) {
            $order_disputes = table('order_dispute')
                ->where('id', $id)
                ->select()->toarray();
        } else {
            $where['update_status'] = 'hidden';
            $order_disputes = table('order_dispute')
                ->order('updatetime asc')
                ->where($where)
                ->limit('20')
                ->select()->toarray();
        }
        $return = array();
        if (!empty($order_disputes)) {
            foreach ($order_disputes as $order_dispute) {
                if($order_dispute['type'] == 'paypal'){
                    // $order = $this->step1_paypal($order_dispute);
                    // if(!empty($order)){
                    //     $return = $this->step4($order_dispute,$order);
                    // }else{
                        $order = $this->step2_paypal($order_dispute);
                        if(!empty($order)){
                            $return = $this->step4($order_dispute,$order);
                        }else{
                            $order = $this->step3_paypal($order_dispute);
                            if(!empty($order)){
                                $return = $this->step4($order_dispute,$order);
                            }else{
                                $return = $this->step5($order_dispute);
                            }
                        }
                    // }
                }else{
                    $order = $this->step0($order_dispute);
                    if(!empty($order)){
                        $return = $this->step4($order_dispute,$order);
                    }else{
                        $order = $this->step1($order_dispute);
                        if(!empty($order)){
                            $return = $this->step4($order_dispute,$order);
                        }else{
                            $order = $this->step2($order_dispute);
                            if(!empty($order)){
                                $return = $this->step4($order_dispute,$order);
                            }else{
                                $order = $this->step3($order_dispute);
                                if(!empty($order)){
                                    $return = $this->step4($order_dispute,$order);
                                }else{
                                    $return = $this->step5($order_dispute);
                                }
                            }
                        }
                    }
                }
                
            }
            return success('更新成功',$return);
        } else {
            return error('未找到相关订单',$return);
        }
    }

    /**
    * 方法详情
    * @param array params
    */
    public function step1_paypal($order_dispute)
    {
        $order = array();
        if(!empty($order_dispute['invoice_number']) && !empty($order_dispute['seller_transaction_id'])){
            $where['authorization'] = $order_dispute['seller_transaction_id'];
            $where['payment_id'] = $order_dispute['invoice_number'];
            $transactions = table('order_transactions')
            ->where($where)
            ->find();
            if(!empty($transactions)){
                $order = table('order')
                    ->where('id', $transactions['order_id'])
                    ->find();
            }
        }
        return $order;
    }

    /**
    * 方法详情
    * @param array params
    */
    public function step2_paypal($order_dispute)
    {
        $order = array();
        if(!empty($order_dispute['seller_transaction_id'])){
            $where['authorization'] = $order_dispute['seller_transaction_id'];
            $transactions = table('order_transactions')
            ->where($where)
            ->find();
            if(!empty($transactions)){
                $order = table('order')
                    ->where('id', $transactions['order_id'])
                    ->find();
            }
        }
        return $order;
    }

    /**
    * 方法详情
    * @param array params
    */
    public function step3_paypal($order_dispute)
    {
        $order = array();
        if(!empty($order_dispute['invoice_number'])){
            $where['payment_id'] = $order_dispute['invoice_number'];
            $transactions = table('order_transactions')
            ->where($where)
            ->find();
            if(!empty($transactions)){
                $order = table('order')
                    ->where('id', $transactions['order_id'])
                    ->find();
            }
        }
        return $order;
    }
    /**
    * 方法详情
    * @param array params
    */
    public function step0($order_dispute)
    {
        $order = array();
        if(!empty($order_dispute['payment_intent'])){
            $where['authorization'] = $order_dispute['payment_intent'];
            $transactions = table('order_transactions')
            ->where($where)
            ->find();
            if(!empty($transactions)){
                $order = table('order')
                    ->where('id', $transactions['order_id'])
                    ->find();
            }
        }
        return $order;
    }
    /**
    * 方法详情
    * @param array params
    */
    public function step1($order_dispute)
    {
        $order = array();
        if(!empty($order_dispute['customer_email_address']) && !empty($order_dispute['customer_name'])){
            $where_dispute['email'] = $order_dispute['customer_email_address'];
            $where_dispute['shipping_name'] = $order_dispute['customer_name'];
            $order = table('order')
            ->where($where_dispute)
            ->find();
        }
        return $order;
    }
    /**
    * 方法详情
    * @param array params
    */
    public function step2($order_dispute)
    {
        $order = array();
        if(!empty($order_dispute['customer_email_address'])){
            $where_dispute['email'] = $order_dispute['customer_email_address'];
            $order = table('order')
            ->where($where_dispute)
            ->find();
        }
        return $order;
    }
    /**
    * 方法详情
    * @param array params
    */
    public function step3($order_dispute)
    {
        $order = array();
        if(!empty($order_dispute['customer_name'])){
            $where_dispute['shipping_name'] = $order_dispute['customer_name'];
            $order = table('order')
            ->where($where_dispute)
            ->find();
        }
        return $order;
    }
    /**
    * 方法详情
    * @param array params
    */
    public function step4($order_dispute,$order)
    {
        $row['updatetime'] = time();
        $row['update_status'] = 'normal';
        $row['site_id'] = $order['site_id'];
        $row['order_name'] = $order['name'];
        $row['order_id'] = $order['id'];
        $return = table('order_dispute')
            ->where('id', $order_dispute['id'])
            ->update($row);
        return $return;
    }
    /**
    * 方法详情
    * @param array params
    */
    public function step5($order_dispute)
    {
        $row['updatetime'] = time();
        $return = table('order_dispute')
            ->where('id', $order_dispute['id'])
            ->update($row);
        return $return;
    }
    /**
     * get请求
     */
    function geturl($url,$api)
    {
        $headerArray = array("Content-Type:application/json;", 'Authorization:Bearer '.$api);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    function geturl_paypal($url,$api)
    {
        $apikey = $api['apikey'];
        $apisecret = $api['apisecret'];
        // Bearer
        $headerArray = array("Content-Type:application/x-www-form-urlencoded;", 'Authorization:Basic ' . base64_encode("$apikey:$apisecret"));
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
    /**
     * 发送post请求
     * 
     */
    function posturl($url, $data = array(), $iscustom = null)
    {
        $data = (is_array($data)) ? json_encode($data, JSON_UNESCAPED_UNICODE) : $data;
        $apikey = $iscustom['apikey'];
        $apisecret = $iscustom['apisecret'];

        $headerArray = array("Content-Type:application/json;", 'Authorization:Basic ' . base64_encode("$apikey:$apisecret"));
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

}
